package com.fowo.api.service.handleWork;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjUtil;
import cn.hutool.core.util.StrUtil;
import com.fowo.api.model.requisition.RequisitionReferAction;
import com.fowo.api.model.requisition.RequisitionVo;
import com.fowo.api.model.requisition.product.RequisitionProductItemVo;
import com.fowo.api.service.RequisitionService;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;

import javax.annotation.Resource;
import java.util.List;

/**
 * 调拨单的提交行为接口
 */
@Component
public class RequisitionRefer implements RequisitionReferAction {

    @Resource
    private RequisitionService requisitionService;

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void run(Long id) throws Exception {
        RequisitionVo requisition = requisitionService.getVoById(id);
        this.prepareRequisitionRefer(requisition);
        // 锁定库存
        requisitionService.lockGoodIinventory(id);
        requisitionService.lockGoodIinventoryBin(id);
//        final Integer badSum = requisition.getRequisitionProduct().stream().filter(t->t.getDefectiveRqtQuantity()!=null).mapToInt(p -> p.getDefectiveRqtQuantity()).sum();
//        if(badSum > 0){
//        }
        requisitionService.lockBadIinventory(id);
        requisitionService.lockBadIinventoryBin(id);

        requisition.setStatus("1");
        requisitionService.update(requisition);
    }

    /**
     * 校验信息
     * @param requisition
     */
    private void prepareRequisitionRefer(RequisitionVo requisition) {
        Assert.notNull(requisition,"调拨单不存在");
        Assert.isTrue(requisition.getStatus().equals("0"),"当前单据状态不可进行此操作！");
        Assert.isTrue(CollUtil.isNotEmpty(requisition.getRequisitionProduct()) &&  requisition.getRequisitionProduct().stream().allMatch(a -> ObjUtil.isAllNotEmpty(a.getProductId(),a.getSku(),a.getFromGoodWarehouseBin(),a.getToGoodWarehouseBin())), "调拨产品信息校验异常,请检查!");
    }
}
